# 
# Project: Last.sk
# File: weeklyalbumchart.py
# Author: Angel Luis Calvo Ortega
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from viewhandler import ViewHandler

# Modes
#  0: None
#  1: name
#  2: artist
#  3: playcount
#  4: chartposition

_PRE = '''
<table cellpadding="0" cellspacing="0">
<tr><td colspan="3"><b><i>Weekly Album Chart</i></b></td></tr>
<tr><td><b>#</b></td><td><b>Album</b></td><td><b>Count</b></td></tr>
'''


class WeeklyAlbumChartHandler(ViewHandler):
    def __init__(self):
        ViewHandler.__init__(self)
        self.PRE = _PRE
        self.POST = '</table>'
        self.ROW = '<tr><td>%s</td><td>%s - %s</td><td>%s</td></tr>'
        self.url = 'http://ws.audioscrobbler.com/1.0/user/%s/weeklyalbumchart.xml'
        self.title = 'Weekly Album Chart'

    def clear(self):
        ViewHandler.clear(self)
        self.mode = 0
        self.name = ''
        self.artist = ''
        self.playcount = ''
        self.chartposition = ''
    
    # SAX methods
    def startElement(self, name, attributes):
        if name == 'name':
            self.mode = 1
        elif name == 'artist':
            self.mode = 2
        elif name == 'playcount':
            self.mode = 3
        elif name == 'chartposition':
            self.mode = 4

    def characters(self, data):
        if self.mode == 1:
            self.name += data
        elif self.mode == 2:
            self.artist += data
        elif self.mode == 3:
            self.playcount += data
        elif self.mode == 4:
            self.chartposition += data
 
    def endElement(self, name):
        self.mode = 0
        if name == 'album':
            self.rows.append(self.ROW % (self.chartposition, self.name, self.artist, self.playcount))
            self.name = ''
            self.artist = ''
            self.playcount = ''
            self.chartposition = ''
